package com.qd.qx.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import android.util.Log;

import com.qd.chatui.enity.MessageInfo;
import com.qd.chatui.widget.EmotionInputDetector;
import com.qd.qx.api.MyXMPPTCPConnection;
import com.qd.qx.bean.ChatConfig;
import com.qd.qx.db.bean.Group;
import com.qd.qx.db.bean.MsgList;
import com.qd.qx.db.bean.People;
import com.qd.qx.db.bean.User;

import java.util.ArrayList;
import java.util.List;

/*
 * 文件名:    DbHelper
 * 创建者:    ys
 * 描述:     TODO
 */
public class DbHelper {

    private SQLiteDatabase db;
    private SqliteHelper dbHelper;

    public DbHelper(Context context) {
        dbHelper = new SqliteHelper(context);
        db = dbHelper.getWritableDatabase();
    }

    public void Close() {
        db.close();
        dbHelper.close();
    }

    /**
     * 根据用户名获取用户id
     *
     * @param userName
     * @return
     */
    private User GetUser(String userName) {
        User user = null;
        Cursor cursor = db.rawQuery("select * from user where user_name=?", new String[]{userName});

        if (cursor.moveToNext()) {
            int user_id = cursor.getInt(cursor.getColumnIndex("user_id"));
            String user_name = cursor.getString(cursor.getColumnIndex("user_name"));
            String user_psd = cursor.getString(cursor.getColumnIndex("user_psd"));
            String user_head_img = cursor.getString(cursor.getColumnIndex("user_head_img"));
            String login_name = cursor.getString(cursor.getColumnIndex("login_name"));
            String real_name = cursor.getString(cursor.getColumnIndex("real_name"));
            //int user_id, String login_name, String user_name, String user_psd, String user_head_img
            user = new User(user_id, login_name, user_name, user_psd, user_head_img, real_name);
        }
        return user;
    }

    /**
     * 登录后插入用户
     *
     * @param loginName
     * @param userName
     * @param userPsd
     * @return
     */
    public User SetUser(String loginName, String userName, String userPsd, String user_head_img, String real_name) {
        User user = GetUser(userName);
        if (user == null) {
            ContentValues values = new ContentValues();
            values.put("user_name", userName);
            values.put("user_psd", userPsd);
            values.put("user_head_img", user_head_img);
            values.put("login_name", loginName);
            values.put("real_name", real_name);
            db.insert("user", null, values);
            user = GetUser(userName);
            return user;
        } else {
            return user;
        }
    }

    /**
     * 插入聊天配置表
     *
     * @param user_code
     * @param only_chatid
     * @param is_ring
     * @param is_membername
     * @param is_save
     */
    public void setChatConfig(String user_code, String only_chatid, int is_ring, int is_membername, int is_save) {
        ContentValues values = new ContentValues();
        values.put("user_code", user_code);
        values.put("only_chatid", only_chatid);
        values.put("is_ring", is_ring);
        values.put("is_membername", is_membername);
        values.put("is_save", is_save);
        db.insert("chat_config", null, values);
    }

    /**
     * 如果有该配置那么更新 否则 插入
     *
     * @param user_code
     * @param only_chatid
     * @param is_ring
     * @param is_membername
     * @param is_save
     */
    public void insertOrUpdateChatConfig(String user_code, String only_chatid, int is_ring, int is_membername, int is_save) {
        ChatConfig chatConfig = getChatConfig(user_code, only_chatid);
        if (null == chatConfig) {
            setChatConfig(user_code, only_chatid, is_ring, is_membername, is_save);
        } else {
            updateChatConfig(user_code, only_chatid, is_ring, is_membername, is_save);
        }
    }

    /**
     * 获取聊天配置表
     *
     * @param userCode
     * @param onlyChatNameId
     * @return
     */
    public ChatConfig getChatConfig(String userCode, String onlyChatNameId) {
        ChatConfig chatConfig = null;
        Cursor cursor = db.rawQuery("select * from chat_config where user_code=? and only_chatid=? ", new String[]{userCode, onlyChatNameId});
        if (cursor.moveToNext()) {
            String user_code = cursor.getString(cursor.getColumnIndex("user_code"));
            String only_chatid = cursor.getString(cursor.getColumnIndex("only_chatid"));
            int is_ring = cursor.getInt(cursor.getColumnIndex("is_ring"));
            int is_membername = cursor.getInt(cursor.getColumnIndex("is_membername"));
            int is_save = cursor.getInt(cursor.getColumnIndex("is_save"));
            chatConfig = new ChatConfig(user_code, only_chatid, is_ring, is_membername, is_save);
        }
        return chatConfig;
    }

    /**
     * 更新聊天配置表
     *
     * @param user_code
     * @param only_chatid
     * @param is_ring
     * @param is_membername
     * @param is_save
     */
    private void updateChatConfig(String user_code, String only_chatid, int is_ring, int is_membername, int is_save) {
        ContentValues values = new ContentValues();
        values.put("user_code", user_code);
        values.put("only_chatid", only_chatid);
        values.put("is_ring", is_ring);
        values.put("is_membername", is_membername);
        values.put("is_save", is_save);
        db.update("chat_config", values, "user_code=? and only_chatid=?", new String[]{user_code, only_chatid});
    }

//    public void inserOrCreatePeople(String userName, String imgs, String real_name, String
//            update_time) {
//        People people = getPeopleInfo(userName);
//        if (null == people) {
//            setPeopleInfo(userName, imgs, real_name, update_time);
//        } else {
//            updatePeopleInfo(userName, imgs, real_name, update_time);
//        }
//    }
//
//    /**
//     * 设置信息（头像）
//     *
//     * @param userName
//     * @param imgs
//     * @return
//     */
//    public void setPeopleInfo(String userName, String imgs, String real_name, String
//            update_time) {
//
//        ContentValues values = new ContentValues();
//        values.put("user_name", userName);
//        values.put("img_url", imgs);
//        values.put("real_name", real_name);
//        values.put("update_time", update_time);
//        db.insert("people_info", null, values);
//    }
//
//    /**
//     * 更新回话头像信息表
//     *
//     * @param userName
//     * @param imgs
//     * @param real_name
//     * @param update_time
//     */
//    private void updatePeopleInfo(String userName, String imgs, String real_name, String
//            update_time) {
//        ContentValues values = new ContentValues();
//        values.put("user_name", userName);
//        values.put("img_url", imgs);
//        values.put("real_name", real_name);
//        values.put("update_time", update_time);
//        db.update("people_info", values, "user_name=?", new String[]{userName});
//    }
//
//    /**
//     * 获取用户信息
//     *
//     * @param userName
//     * @return
//     */
//    public People getPeopleInfo(String userName) {
//        People people = null;
//        Cursor cursor = db.rawQuery("select * from people_info where user_name=?", new String[]{userName});
//
//        if (cursor.moveToNext()) {
//            int people_id = cursor.getInt(cursor.getColumnIndex("people_id"));
//            String user_name = cursor.getString(cursor.getColumnIndex("user_name"));
//            String img = cursor.getString(cursor.getColumnIndex("img_url"));
//            String real_name = cursor.getString(cursor.getColumnIndex("real_name"));
//            String update_time = cursor.getString(cursor.getColumnIndex("update_time"));
//            people = new People(user_name, img, real_name, update_time);
//        }
//        return people;
//    }

    /**
     * 新建或更新群信息
     *
     * @param userName
     * @param real_name
     * @param members
     */
    public void inserOrCreateGroupInfo(String userName, String members, String real_name, String update_time) {
        Group group = getGroupInfo(userName);
        if (null == group) {
            setGroupInfo(userName, members, real_name, update_time);
        } else {
            updateGroupInfo(userName, members, real_name, update_time);
        }
    }

    /**
     * 记录群信息
     *
     * @param userName
     * @param members
     * @param real_name
     * @param update_time
     */
    public void setGroupInfo(String userName, String members, String real_name,
                             String update_time) {
        ContentValues values = new ContentValues();
        values.put("user_name", userName);
        values.put("members", members);
        values.put("real_name", real_name);
        values.put("update_time", update_time);
        db.insert("group_info", null, values);
    }

    /**
     * 更新群信息
     *
     * @param userName
     * @param members
     * @param real_name
     * @param update_time
     */
    private void updateGroupInfo(String userName, String
            members, String real_name, String update_time) {
        ContentValues values = new ContentValues();
        values.put("user_name", userName);
        values.put("members", members);
        values.put("real_name", real_name);
        values.put("update_time", update_time);
        db.update("group_info", values, "user_name=?", new String[]{userName});
    }

    /**
     * 获取群成员信息
     *
     * @param userName
     * @return
     */
    public Group getGroupInfo(String userName) {
        Group groupInfoBean = null;
        Cursor cursor = db.rawQuery("select * from group_info where user_name=?", new String[]{userName});
        if (cursor.moveToNext()) {
            int groupinfo_id = cursor.getInt(cursor.getColumnIndex("groupinfo_id"));
            String user_name = cursor.getString(cursor.getColumnIndex("user_name"));
            String members = cursor.getString(cursor.getColumnIndex("members"));
            String real_name = cursor.getString(cursor.getColumnIndex("real_name"));
            String update_time = cursor.getString(cursor.getColumnIndex("update_time"));
            groupInfoBean = new Group(user_name, members, real_name, update_time);
        }
        return groupInfoBean;
    }

    /**
     * 获取聊天列表
     *
     * @param userId
     * @return
     */
    public List<MsgList> getMsgAllList(int userId) {
        List<MsgList> list = new ArrayList<>();
        Cursor cursor = db.rawQuery("select * from msg_list where user_id=? order by top_time  desc , last_msg_time      desc", new String[]{userId + ""});
        while (cursor.moveToNext()) {
            int msg_list_id = cursor.getInt(cursor.getColumnIndex("msg_list_id"));
            int user_id = cursor.getInt(cursor.getColumnIndex("user_id"));
            String to_name = cursor.getString(cursor.getColumnIndex("to_name"));
            String last_msg = cursor.getString(cursor.getColumnIndex("last_msg"));
            String last_msg_time = cursor.getString(cursor.getColumnIndex("last_msg_time"));
            int msg_list_type = cursor.getInt(cursor.getColumnIndex("msg_list_type"));
            int unread_count = cursor.getInt(cursor.getColumnIndex("unread_count"));
            String top_time = cursor.getString(cursor.getColumnIndex("top_time"));
            String real_name = cursor.getString(cursor.getColumnIndex("real_name"));
            MsgList msgList = new MsgList(msg_list_id, user_id, to_name, last_msg, last_msg_time, msg_list_type, unread_count, top_time, real_name);
            list.add(msgList);
        }
        return list;
    }

    /**
     * 获取对应的人的聊天列表
     *
     * @param userId
     * @return
     */
    public MsgList getMsgList(int userId, String toName) {
        MsgList msgList = null;
        try {
            Cursor cursor = db.rawQuery("select * from msg_list where user_id=? and to_name=? ", new String[]{userId + "", toName});
            while (cursor.moveToNext()) {
                int msg_list_id = cursor.getInt(cursor.getColumnIndex("msg_list_id"));
                int user_id = cursor.getInt(cursor.getColumnIndex("user_id"));
                String to_name = cursor.getString(cursor.getColumnIndex("to_name"));
                String last_msg = cursor.getString(cursor.getColumnIndex("last_msg"));
                String last_msg_time = cursor.getString(cursor.getColumnIndex("last_msg_time"));
                int msg_list_type = cursor.getInt(cursor.getColumnIndex("msg_list_type"));
                int unread_count = cursor.getInt(cursor.getColumnIndex("unread_count"));
                String top_time = cursor.getString(cursor.getColumnIndex("top_time"));
                String real_name = cursor.getString(cursor.getColumnIndex("real_name"));
                msgList = new MsgList(msg_list_id, user_id, to_name, last_msg, last_msg_time, msg_list_type, unread_count, top_time, real_name);
            }
        } catch (Exception e) {
            Log.e("error", "getMsgList: " + e.toString());
        }

        return msgList;
    }

    /**
     * 插入一条和某某聊天的消息list
     *
     * @param userId
     * @param to_name
     * @param last_msg
     * @param last_msg_time
     * @param msg_list_type
     */
    public MsgList insertMsgList(int userId, String to_name, String last_msg, String
            last_msg_time, int msg_list_type, int unread_count, String real_name) {
        db.execSQL("insert into msg_list(user_id,to_name,last_msg,last_msg_time,msg_list_type,unread_count,top_time,real_name) values(?,?,?,?,?,?,?,?)",
                new Object[]{userId, to_name, last_msg, last_msg_time, msg_list_type, unread_count, "", real_name});
        MsgList msgList = getMsgList(userId, to_name);
        return msgList;
    }

    /**
     * 检查是否有和对应人聊天的msg_list_id
     *
     * @param userId
     * @param toName
     * @return
     */
    public MsgList checkMsgList(int userId, String toName, String real_name) {
        MsgList msgList = null;
        msgList = getMsgList(userId, toName);
        if (msgList == null) {
            insertMsgList(userId, toName, "", "", 1, 0, real_name);
            msgList = getMsgList(userId, toName);
        }
        return msgList;
    }

    /**
     * 更新消息列表表中最后一条消息，用户消息列表显示
     *
     * @param userId
     * @param msg_list_id
     * @param last_msg
     * @param last_msg_time
     */
    private void updateMsgList(int userId, int msg_list_id, String last_msg, String
            last_msg_time, int unread_count) {
//        db.execSQL("update msg_list where user_id=? and to_name=? set last_msg=? and last_msg_time=?", new Object[]{userId});
        ContentValues values = new ContentValues();
        values.put("last_msg", last_msg);
        values.put("last_msg_time", last_msg_time);
        //未读不为0的时候才更新
        if (0 != unread_count) {
            values.put("unread_count", unread_count);
        }
        db.update("msg_list", values, "user_id=? and msg_list_id=?", new String[]{userId + "", msg_list_id + ""});
    }

    /**
     * 更新数据库会话列表名字
     *
     * @param userId
     * @param msg_list_id
     * @param newRealName
     */
    public void updateNameMsgList(int userId, int msg_list_id, String newRealName) {
        ContentValues values = new ContentValues();
        values.put("real_name", newRealName);
        db.update("msg_list", values, "user_id=? and msg_list_id=?", new String[]{userId + "", msg_list_id + ""});
    }


    /**
     * 重新设置未读消息数
     *
     * @param userId
     * @param msg_list_id
     */
    public void markUnreadCount(int userId, int msg_list_id) {
//        db.execSQL("update msg_list where user_id=? and to_name=? set last_msg=? and last_msg_time=?", new Object[]{userId});
        ContentValues values = new ContentValues();
        values.put("unread_count", 0);
        db.update("msg_list", values, "user_id=? and msg_list_id=?", new String[]{userId + "", msg_list_id + ""});
    }

    /**
     * 设置置顶时间 top_time为"" 不置顶
     *
     * @param userId
     * @param msg_list_id
     * @param top_time
     */
    public void resetTopTime(int userId, int msg_list_id, String top_time) {
        ContentValues values = new ContentValues();
        values.put("top_time", top_time);
        db.update("msg_list", values, "user_id=? and msg_list_id=?", new String[]{userId + "", msg_list_id + ""});
    }

    /**
     * 重置所有未读消息数
     *
     * @param userId
     */
    public void markAllUnreadCount(int userId) {
        List<MsgList> msgLists = getMsgAllList(userId);
        if (null != msgLists) {
            for (MsgList msgListBean : msgLists) {
                markUnreadCount(userId, msgListBean.getMsg_list_id());
            }
        }
    }


    /**
     * 重置单条消息的状态
     *
     * @param msg_chatid
     */
    public void updateMsgState(String msg_chatid, int sendState) {
        ContentValues values = new ContentValues();
        values.put("send_state", sendState);
        db.update("msg", values, "msg_chatid=? ", new String[]{msg_chatid + ""});
    }

    /**
     * 插入消息
     *
     * @param msg_list_id  对应的会话id
     * @param msg_chatid   消息id
     * @param from_name    名字+@+域名
     * @param msg_content
     * @param msg_sendtime
     * @param msg_type
     * @param from_type    类型 区分左右显示
     * @param sendState    消息状态
     * @param header       头像
     */
    private void insertMsg(int msg_list_id, String msg_chatid, String from_name, String
            msg_content,
                           String msg_sendtime, String msg_type, int from_type,
                           int sendState, String header, String real_name) {
        ContentValues values = new ContentValues();
        values.put("msg_list_id", msg_list_id);
        values.put("msg_chatid", msg_chatid);
        values.put("from_name", from_name);
        values.put("msg_content", msg_content);
        values.put("msg_sendtime", msg_sendtime);
        values.put("msg_type", msg_type);
        values.put("from_type", from_type);
        values.put("send_state", sendState);
        values.put("header", header);
        values.put("real_name", real_name);
        db.insert("msg", null, values);
    }

    /**
     * 插入一条消息消息
     *
     * @param user_id
     * @param to_name      会话对象id
     * @param msg_content
     * @param msg_sendtime
     * @param send_name    该消息的发送者
     * @param isAddUnread  是否添加一条未读
     */
    public void insertOneMsg(int user_id, String to_name, String msg_chatid, String
            msg_content, String msg_sendtime, String send_name, int from_type,
                             String msgType, int sendState, String header,
                             boolean isAddUnread, String to_real_name, String send_real_name, String roomName) {
        String msgListLastShow = getTextShow(msgType, msg_content);
        MsgList msgList = null;
        msgList = getMsgList(user_id, to_name);
        int unread_count = 0;
        if (msgList == null) {
            if (isAddUnread) {
                unread_count = 1;
            }
            if (TextUtils.isEmpty(roomName)) {
                msgList = insertMsgList(user_id, to_name, msgListLastShow, msg_sendtime, from_type, unread_count, to_real_name);
            } else {
                //roomname 不为空的话 那么列表名字显示群名字
                msgList = insertMsgList(user_id, to_name, msgListLastShow, msg_sendtime, from_type, unread_count, roomName);
            }
        } else {
            if (isAddUnread) {
                unread_count = msgList.getUnread_count() + 1;
            }
            updateMsgList(user_id, msgList.getMsg_list_id(), msgListLastShow, msg_sendtime, unread_count);
        }
        insertMsg(msgList.getMsg_list_id(), msg_chatid, send_name, msg_content, msg_sendtime, msgType, from_type, sendState, header, send_real_name);
    }

    /**
     * 设置回话列表最后一条消息的特殊显示方式
     *
     * @param msgType
     * @param lastMsg
     * @return
     */
    public String getTextShow(String msgType, String lastMsg) {
        String textShow = "";
        switch (msgType) {
            case EmotionInputDetector.sendType_Text:
                textShow = lastMsg;
                break;
            case EmotionInputDetector.sendType_Audio:
                textShow = "[语音]";
                break;
            case EmotionInputDetector.sendType_Img:
                textShow = "[图片]";
                break;
            case EmotionInputDetector.sendType_File:
                textShow = "[文件]";
                break;
            case EmotionInputDetector.sendType_Video:
                textShow = "[视频]";
                break;
            case EmotionInputDetector.sendType_Tips:
                textShow = lastMsg;
                break;
        }
        return textShow;
    }

    /**
     * 获取和某某聊天的消息
     *
     * @param msg_list_id
     * @param page
     */
    public List<MessageInfo> getAllMsg(int msg_list_id, int page) {
        List<MessageInfo> list = new ArrayList<>();
        //  List<MessageInfo> resultList = new ArrayList<>();
        // int endIndex = page * 2;


        // Cursor cursor = db.rawQuery("select * from msg where msg_list_id=? LIMIT 0,? ", new String[]{msg_list_id + "", endIndex + ""});
        Cursor cursor = db.rawQuery("select * from msg where msg_list_id=? ", new String[]{msg_list_id + ""});
        while (cursor.moveToNext()) {
            int msg_id = cursor.getInt(cursor.getColumnIndex("msg_id"));
            String from_name = cursor.getString(cursor.getColumnIndex("from_name"));
            String msg_chatid = cursor.getString(cursor.getColumnIndex("msg_chatid"));
            String msg_content = cursor.getString(cursor.getColumnIndex("msg_content"));
            String msg_sendtime = cursor.getString(cursor.getColumnIndex("msg_sendtime"));
            String msg_type = cursor.getString(cursor.getColumnIndex("msg_type"));
            int from_type = cursor.getInt(cursor.getColumnIndex("from_type"));
            int send_state = cursor.getInt(cursor.getColumnIndex("send_state"));
            String header = cursor.getString(cursor.getColumnIndex("header"));
            String real_name = cursor.getString(cursor.getColumnIndex("real_name"));
//            构造(int msgId, int msgListId, String msgChatId, String fromName, String content,
//                    String sendTime, String msgType, int type, int sendState, String header)
            MessageInfo msg = new MessageInfo(msg_id, msg_list_id, msg_chatid, from_name, msg_content, msg_sendtime, msg_type, from_type
                    , send_state, header, real_name);
            list.add(msg);
        }
//        for (int i = 2 * (page - 1); i < 2 * (page); i++) {
//            if (i >= list.size()) {
//                break;
//            }
//            resultList.add(list.get(i));
//        }
        return list;
    }

    /**
     * 根据msglistid 删除对应列表
     *
     * @param msg_list_id
     */
    public void deleteChat(int msg_list_id) {
        db.delete("msg_list", "msg_list_id=?", new String[]{msg_list_id + ""});
        db.delete("msg", "msg_list_id=?", new String[]{msg_list_id + ""});
    }

    /**
     * 根据msglistid 清空聊天记录
     *
     * @param msg_list_id
     */
    public void clearChatMessage(int uerid, int msg_list_id) {
        db.delete("msg", "msg_list_id=?", new String[]{msg_list_id + ""});
        updateMsgList(uerid, msg_list_id, "", "", 0);
    }

    /**
     * 清空所有的聊天记录
     */
    public void clearAllChatMessage() {
        int userid = MyXMPPTCPConnection.getInstance().GetUser().getUser_id();
        List<MsgList> msgLists = getMsgAllList(userid);
        if (null != msgLists) {
            for (MsgList msg : msgLists) {
                clearChatMessage(userid, msg.getMsg_list_id());
            }
        }
    }

}
